// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.datainterface.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.*;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.query.QueryGenerator;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.datainterface.constants.Constants;
import com.fowo.api.datainterface.constants.DataTypeKind;
import com.fowo.api.datainterface.constants.DatainterfaceTypeKind;
import com.fowo.api.datainterface.constants.RequestFieldTypeKind;
import com.fowo.api.datainterface.entity.Datainterface;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.entity.DatainterfaceLog;
import com.fowo.api.datainterface.mapper.DatainterfaceMapper;
import com.fowo.api.datainterface.model.DataContextModel;
import com.fowo.api.datainterface.model.DataInterfaceModel;
import com.fowo.api.datainterface.model.DatainterfaceSearchParamPo;
import com.fowo.api.datainterface.model.DatainterfaceVo;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.datainterface.service.DatainterfaceService;
import com.fowo.api.datainterface.service.serviceCore.BaseFromService;
import com.fowo.api.datainterface.service.serviceCore.BaseInvokeService;
import com.fowo.api.datainterface.service.serviceCore.BaseRetryService;
import com.fowo.api.datainterface.service.serviceCore.BaseToService;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.datainterface.util.JScriptUtil;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.sql.DataSource;
import javax.validation.Validator;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 接口 服务实现基类
 */
@Service
@Slf4j
@DS("ds21")
public class DatainterfaceServiceImpl
        extends ServiceImpl<DatainterfaceMapper, Datainterface>
        implements DatainterfaceService {

    public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
    // 导出时单次查询最大记录数
    protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
    // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
    protected static final long EXPORT_MAX_SIZE = 1048575;

    @Resource
    protected FileService fileService;

    @Resource
    protected SysImportTemplateService importTemplateService;

    @Resource
    protected Validator validator;

    @Resource
    private Common common;

    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private List<BaseFromService> fromServiceList;
    @Resource
    private List<BaseToService> toServiceList;
    @Resource
    private List<BaseInvokeService> invokeServiceList;
    @Resource
    private SysSerialService sysSerialService;

    @Resource
    private List<BaseRetryService> retryServiceList;
    private NamedParameterJdbcTemplate jdbcTemplate;

    public NamedParameterJdbcTemplate getJdbcTemplate() {
        if (jdbcTemplate == null) {
            jdbcTemplate = new NamedParameterJdbcTemplate(ContextHolder.getApplicationContext().getBean(DataSource.class));
        }
        return jdbcTemplate;
    }
    /**
     * 创建接口
     *
     * @param model 接口
     * @return 新数据的主键
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(DatainterfaceVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        Datainterface entity = new Datainterface();
        BeanUtils.copyProperties(model, entity);
        entity.setCreateTime(new Date());
        entity.setLastUpdateTime(new Date());
        if (currentUser != null) {
            entity.setCreateUser(currentUser.getUserId());
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        if (this.save(entity)) {
            return entity.getId();
        }
        throw new Exception("接口保存失败");
    }

    /**
     * 更新接口
     *
     * @param model 接口
     * @return 更新是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(DatainterfaceVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        Datainterface entity = this.getById(model.getId());
        if (entity == null) {
            throw new Exception("接口不存在");
        }
        BeanUtils.copyProperties(
                model,
                entity,
                "id",
                "lastUpdateUser",
                "lastUpdateTime",
                "createUser",
                "createTime"
        );
        entity.setLastUpdateTime(new Date());
        if (currentUser != null) {
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        if (this.updateById(entity)) {
            return true;
        }
        return false;
    }

    /**
     * 更新接口（带空值）
     *
     * @param model 接口
     * @return 更新是否成功
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateForEdit(DatainterfaceVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        Datainterface entity = this.getById(model.getId());
        if (entity == null) {
            throw new Exception("接口不存在");
        }
        model.setLastUpdateTime(new Date());
        if (currentUser != null) {
            model.setLastUpdateUser(currentUser.getUserId());
        }
        boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
                .set(Datainterface::getRequestParams, model.getRequestParams())
                .set(Datainterface::getConvertRuleMapFrom, model.getConvertRuleMapFrom())
                .set(Datainterface::getRetryTimes, model.getRetryTimes())
                .set(Datainterface::getDataProcessing, model.getDataProcessing())
                .set(Datainterface::getParamsPlace, model.getParamsPlace())
                .set(Datainterface::getRequestHeaders, model.getRequestHeaders())
                .set(Datainterface::getCheckType, model.getCheckType())
                .set(Datainterface::getDataType, model.getDataType())
                .set(Datainterface::getDescriptions, model.getDescriptions())
                .set(Datainterface::getEnabledMark, model.getEnabledMark())
                .set(Datainterface::getSortCode, model.getSortCode())
                .set(Datainterface::getQueryStatement, model.getQueryStatement())
                .set(Datainterface::getRequestMethod, model.getRequestMethod())
                .set(Datainterface::getInterfaceUrl, model.getInterfaceUrl())
                .set(Datainterface::getFullName, model.getFullName())
                .set(Datainterface::getEnCode, model.getEnCode())
                .set(Datainterface::getAppCode, model.getAppCode())
                .set(Datainterface::getLastUpdateUser, model.getLastUpdateUser())
                .set(Datainterface::getLastUpdateTime, model.getLastUpdateTime())
                .eq(Datainterface::getId, model.getId())
                .update();
        if (isOk) {
        }
        return isOk;
    }

    /**
     * 删除接口
     *
     * @param id 接口的主键
     * @return 删除是否成功
     */
    @Override
    public boolean delete(Long id) throws Exception {
        return this.removeById(id);
    }

    /**
     * 批量删除接口
     *
     * @param ids 接口的主键列表
     * @return 删除是否成功
     */
    @Override
    public boolean batchDelete(List<Long> ids) throws Exception {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 通过请求参数查询接口主键(重复时返回最新的主键)
     */
    @Override
    public Long getIdByRequestParams(String requestParams) {
        return this.getObj(Wrappers.<Datainterface>lambdaQuery().select(Datainterface::getId).eq(Datainterface::getRequestParams, requestParams), res -> Convert.toLong(res));
    }

    /**
     * 通过请求参数查询接口多主键(重复时返回最新的主键)
     */
    @Override
    public List<Long> getIdsByRequestParams(List<String> list) {
        return this.listObjs(Wrappers.<Datainterface>lambdaQuery().select(Datainterface::getId).in(Datainterface::getRequestParams, list), res -> Convert.toLong(res));
    }

    /**
     * 通过接口主键查询请求参数
     */
    @Override
    public String getRequestParamsById(Long id) {
        return this.getObj(Wrappers.<Datainterface>lambdaQuery().select(Datainterface::getRequestParams).eq(Datainterface::getId, id), res -> Convert.toStr(res));
    }

    /**
     * 通过接口主键查询请求参数列表
     */
    @Override
    public List<String> getRequestParamsByIds(List<Long> ids) {
        return this.listObjs(Wrappers.<Datainterface>lambdaQuery().select(Datainterface::getRequestParams).in(Datainterface::getId, ids), res -> Convert.toStr(res));
    }

    /**
     * 获取详情
     *
     * @param id 接口的主键
     */
    @Override
    public DatainterfaceVo getVoById(Long id) throws Exception {
        Datainterface vo = this.getById(id);
        if (vo == null) {
            return null;
        }
        return BeanUtil.copyProperties(vo, DatainterfaceVo.class);
    }

    /**
     * 分页查询接口
     *
     * @param search 查询条件
     * @return 接口分页查询结果
     */
    @Override
    public Page<Datainterface> pageSearch(
            DatainterfaceSearchParamPo search
    ) {
        Datainterface datainterface = BeanUtil.copyProperties(search, Datainterface.class);
        QueryWrapper<Datainterface> queryWrapper = QueryGenerator.initQueryWrapper(datainterface, search);
        Page<Datainterface> pageList = this.page(search.toPage(), queryWrapper);
        return pageList;

    }

    /**
     * 列表查询接口
     *
     * @param search 查询条件
     * @return 接口列表查询结果
     */
    @Override
    public List<Datainterface> search(DatainterfaceSearchParamPo search) {
        Datainterface datainterface = BeanUtil.copyProperties(search, Datainterface.class);
        QueryWrapper<Datainterface> queryWrapper = QueryGenerator.initQueryWrapper(datainterface, search);
        return this.list(queryWrapper);
    }

    /**
     * 查询接口最后更新时间
     *
     * @param search 查询条件
     * @return 接口最后更新时间
     */
    @Override
    public Date searchLastUpdateTime(DatainterfaceSearchParamPo search) {
        Datainterface datainterface = BeanUtil.copyProperties(search, Datainterface.class);
        QueryWrapper<Datainterface> queryWrapper = QueryGenerator.initQueryWrapper(datainterface, search, null, null);
        queryWrapper.select("max(last_update_time) last_update_time");
        return this.getObj(queryWrapper, res -> Convert.toDate(res));
    }







    /**
     * 测试方法
     */
    @Transactional(rollbackFor = Exception.class)
    public void testTran(Integer a) {
        Integer x = 1 / a;
        JSONObject map1 = new JSONObject();
        map1.put("a", "1");
        map1.put("b", "2");
        map1.put("c", "3");
        map1.put("d", "111");
        JSONObject map2 = new JSONObject();
        map2.put("a", "4");
        map2.put("b", "5");
        map2.put("c", 6);
        map2.put("d", "111");
        JSONObject map3 = new JSONObject();
        map3.put("a", "7");
        map3.put("b", "8");
        map3.put("c", "9");
        map3.put("d", "111");
        JSONObject[] array = ArrayUtil.toArray(CollUtil.newArrayList(map1, map2, map3), JSONObject.class);
        //int[] ints = sqlManager.executeBatchTemplateUpdate("insert into test(a,b,c) values (#{a},#{b},#{c})", list);
        int[] ints = getJdbcTemplate().batchUpdate("insert into test(a,b,c) values (:a,:b,:c)", array);
    }

    /**
     * 拷贝
     *
     * @param id
     * @return
     */
    @Override
    public Boolean copy(Long id) {
        Datainterface entity = this.getById(id);
        String number = sysSerialService.getNewSerial(new NewSerialRequest(null, "Datainterface.encode"));
        entity.setEnCode(number);
        entity.setFullName(entity.getFullName() + ".副本" + RandomUtil.randomNumbers(5));
        Datainterface entity1 = BeanUtil.copyProperties(entity, Datainterface.class, "id");
        return this.save(entity1);
    }

    /**
     * 直接调用接口
     *
     * @param id
     * @param enCode
     * @param queryStatement
     * @param currentParamsMap
     * @param currentHeadersMap
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object executeInterface(Long id, String enCode, String queryStatement, Object currentParamsMap, Object currentHeadersMap) {
        Object info = null;
        Assert.isTrue(StrUtil.isNotEmpty(StrUtil.toStringOrNull(id)) || StrUtil.isNotEmpty(enCode) || StrUtil.isNotEmpty(queryStatement), "参数错误！");
        Datainterface entity = this.getOne(Wrappers.<Datainterface>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(id), Datainterface::getId, id)
                .eq(StrUtil.isNotEmpty(enCode), Datainterface::getEnCode, enCode)
                .eq(StrUtil.isNotEmpty(queryStatement), Datainterface::getQueryStatement, queryStatement), false);
        DataContextModel.DatainterfaceInvokeModel invoke = initDatainterfaceInvokeModel(entity);
        //执行接口
        if (StrUtil.equalsIgnoreCase(DatainterfaceTypeKind.Invoke.getValue(), invoke.getType())) {
            info = executeInterfaceByContextInvoke(invoke, currentParamsMap, JsonUtil.getJsonToBean(currentHeadersMap, JSONObject.class));
            //来源接口
        } else if (StrUtil.equalsIgnoreCase(DatainterfaceTypeKind.From.getValue(), invoke.getType())) {
            DataContextModel.DatainterfaceFromModel from = new DataContextModel().new DatainterfaceFromModel();
            BeanUtil.copyProperties(invoke, from);
            info = executeInterfaceByContextFrom(from, JsonUtil.getJsonToBean(currentParamsMap, JSONObject.class), JsonUtil.getJsonToBean(currentHeadersMap, JSONObject.class));
            //更新模版参数
            try {
                entity.setConvertRuleMapFrom(JsonUtil.getObjectToString(CollUtil.getFirst(JsonUtil.getJsonToJsonArray(info))));
            } catch (Exception e) {
                entity.setConvertRuleMapFrom(JsonUtil.getObjectToString(info));
            }
            this.updateById(entity);
            return info;
        } else {
            Assert.isTrue(false, "接口类型不支持预览，请检查配置");
        }

        return info;
    }
    /**
     * 初始化接口信息
     *
     * @param entity
     * @return
     */
    private DataContextModel.DatainterfaceInvokeModel initDatainterfaceInvokeModel(Datainterface entity) {
        Assert.isTrue(ObjectUtil.isNotEmpty(entity), "未找到接口信息，请检查配置");
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode, entity.getAppCode()), false);
        Assert.isTrue(ObjectUtil.isNotEmpty(entityAuthority), "未找到接口 {} 授权信息，请检查配置", entity.getEnCode());
        DataContextModel.DatainterfaceAuthorityModel datainterfaceAuthorityModel = new DataContextModel().new DatainterfaceAuthorityModel();
        BeanUtil.copyProperties(entityAuthority, datainterfaceAuthorityModel);
        DataContextModel.DatainterfaceInvokeModel invoke = new DataContextModel().new DatainterfaceInvokeModel();
        BeanUtil.copyProperties(entity, invoke);
        invoke.setAuthority(datainterfaceAuthorityModel);
        return invoke;
    }

    /**
     * From调用入口
     *
     * @param invoke            接口
     * @param currentParamsMap  运行时请求参数
     * @param currentHeadersMap 运行时请求头参数
     * @return
     */
    @Override
    public Object executeInterfaceByContextInvoke(DataContextModel.DatainterfaceInvokeModel invoke, Object currentParamsMap, JSONObject currentHeadersMap) {
        Assert.isTrue(ObjectUtil.isNotEmpty(invoke), "未找到执行接口信息，请检查配置");
        Assert.isTrue(ObjectUtil.isNotEmpty(invoke.getAuthority()), "未找到执行接口 {} 授权信息，请检查配置", invoke.getEnCode());
        //封装参数
        Optional<BaseInvokeService> baseService = StreamUtil.of(invokeServiceList).filter(f -> StrUtil.equalsIgnoreCase(f.getType().getValue(), invoke.getDataType())).findFirst();
        if (baseService.isPresent()) {
            return baseService.get().invoke(invoke, currentParamsMap, currentHeadersMap);
        } else {
            return SpringUtil.getBean(JScriptUtil.class).callJsInvoke(invoke.getDataProcessing(), currentParamsMap == null ? new JSONObject() : currentParamsMap, null, null);
        }
    }


    /**
     * From调用入口
     *
     * @param from              接口
     * @param currentParamsMap  运行时请求参数
     * @param currentHeadersMap 运行时请求头参数
     * @return
     */
    @Override
    public Object executeInterfaceByContextFrom(DataContextModel.DatainterfaceFromModel from, JSONObject currentParamsMap, JSONObject currentHeadersMap) {
        Assert.isTrue(ObjectUtil.isNotEmpty(from), "未找到来源接口信息，请检查配置");
        Assert.isTrue(ObjectUtil.isNotEmpty(from.getAuthority()), "未找到来源接口 {} 授权信息，请检查配置", from.getEnCode());
        //封装参数
        currentParamsMap = getParams(from, from.getTaskCode(), currentParamsMap);
        if (StrUtil.equalsIgnoreCase(DataTypeKind.Api.getValue(), from.getDataType())) {
            from.setInterfaceUrl(common.convertRequestPath(from.getAuthority().getRootPath(), from.getInterfaceUrl()));
        }
        Optional<BaseFromService> baseService = StreamUtil.of(fromServiceList).filter(f -> StrUtil.equalsIgnoreCase(f.getType().getValue(), from.getDataType())).findFirst();
        if (baseService.isPresent()) {
            return baseService.get().invokeFrom(from, currentParamsMap, currentHeadersMap);
        } else {
            Assert.isTrue(false, "{} 来源接口 {}暂不支持的来源类型 {}", StrUtil.concat(true, from.getTaskCode()), from.getEnCode(), from.getDataType());
        }
        return null;
    }


    /**
     * From调用入口
     *
     * @param to                接口
     * @param currentParamsMap  运行时请求参数
     * @param currentHeadersMap 运行时请求头参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object executeInterfaceByContextTo(DataContextModel.DatainterfaceToModel to, JSONObject currentParamsMap, JSONObject currentHeadersMap) {
        Assert.isTrue(ObjectUtil.isNotEmpty(to), "未找到目标接口信息，请检查配置");
        Assert.isTrue(ObjectUtil.isNotEmpty(to.getAuthority()), "未找到目标接口 {} 授权信息，请检查配置", to.getEnCode());
        //封装参数
        currentParamsMap = getParams(to, to.getTaskCode(), currentParamsMap);
        if (StrUtil.equalsIgnoreCase(DataTypeKind.Api.getValue(), to.getDataType())) {
            to.setInterfaceUrl(common.convertRequestPath(to.getAuthority().getRootPath(), to.getInterfaceUrl()));
        }
        Optional<BaseToService> baseService = StreamUtil.of(toServiceList).filter(f -> StrUtil.equalsIgnoreCase(f.getType().getValue(), to.getDataType())).findFirst();
        if (baseService.isPresent()) {
            //预览环境保存入参展示
            if (StrUtil.equalsIgnoreCase(Constants.Produce, to.getEnvironment())) {
                baseService.get().invokeTo(to, currentParamsMap, currentHeadersMap);
            } else {
                if (MapUtil.isNotEmpty(to.getMappingSuccessData())) {
                    to.setCallJsData(to.getMappingSuccessData());
                }

            }
            to.setMappingSuccessData(null);
            log.info(StrUtil.format("请求参数 {} 成功，目标接口请求结果： {} ", to.getRequestParams(), currentParamsMap));

        } else {
            Assert.isTrue(false, "{} 目标接口 {}暂不支持的目标类型 {}", StrUtil.concat(true, to.getTaskCode()), to.getEnCode(), to.getDataType());
        }
        return currentParamsMap;
    }

    /**
     * 校验封装参数
     *
     * @param dt
     * @param taskCode
     * @param currentParamsMap
     * @return
     */
    private JSONObject getParams(Datainterface dt, String taskCode, JSONObject currentParamsMap) {
        Boolean checkType = Convert.toBool(dt.getCheckType(), false);
        if (checkType) {
            // 验证参数必填或类型
            String checkRequestParams = checkRequestParams(dt.getRequestParams(), currentParamsMap);
            Assert.isTrue(StrUtil.isEmpty(checkRequestParams), "{} 接口 {},请求时验证参数必填或类型错误", StrUtil.concat(true, taskCode), dt.getEnCode(), checkRequestParams);
        }
        List<JSONObject> jsonToListMap = null;
        //参数默认值替换
        try {
            jsonToListMap = JsonUtil.getJsonToList(dt.getRequestParams());
        } catch (Exception ex) {
            throw new RuntimeException(StrUtil.format("{}  接口 {} 转换参数 {} 时发生异常 ", StrUtil.concat(true, taskCode), dt.getEnCode(), StrUtil.subPre(JsonUtil.getObjectToString(dt.getRequestParams()), 500)), ex);
        }
        currentParamsMap = common.convertCurrentMap(currentParamsMap, jsonToListMap);
        return currentParamsMap;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public Boolean executeInterfaceByContextretry(DatainterfaceLog log) {
        Assert.isTrue(ObjectUtil.isNotEmpty(log) && StrUtil.isAllNotEmpty(log.getUrl()), "参数错误！");
        Datainterface entity = this.getOne(Wrappers.<Datainterface>lambdaQuery().eq(StrUtil.isNotEmpty(log.getEnCode()), Datainterface::getEnCode, log.getEnCode())
                .eq(StrUtil.isNotEmpty(log.getUrl()), Datainterface::getQueryStatement, log.getUrl()), false);
        Optional<BaseRetryService> baseService;
        DataContextModel.DatainterfaceInvokeModel invoke;
        if (ObjUtil.isEmpty(entity)) {
            entity = new Datainterface();
            entity.setAppCode(log.getAppCode());
            entity.setDataType(log.getBusinessType());
            invoke = initDatainterfaceInvokeModel(entity);
        } else {
            invoke = initDatainterfaceInvokeModel(entity);
        }
        if (StrUtil.equalsIgnoreCase(DataTypeKind.Api.getValue(), invoke.getDataType())) {
            invoke.setInterfaceUrl(common.convertRequestPath(invoke.getAuthority().getRootPath(), invoke.getInterfaceUrl()));
        }
        baseService = StreamUtil.of(retryServiceList).filter(f -> StrUtil.equalsIgnoreCase(f.getType().getValue(), invoke.getDataType()) || StrUtil.containsAnyIgnoreCase(f.getType().getValue(), invoke.getDataType())).findFirst();
        if (baseService.isPresent()) {
            Object param = null;
            try {
                param = JsonUtil.getJsonToBean(log.getRequestContent(), JSONObject.class);
            } catch (Exception ex) {
                try {
                    param = JsonUtil.getJsonToJsonArray(log.getRequestContent());
                } catch (Exception exx) {
                    param = log.getRequestContent();
                }
            }
            return baseService.get().retryInvokeTo(invoke, log);
        } else {
            Assert.isTrue(false, "重试接口 {} 暂不支持的类型 {}", invoke.getEnCode(), invoke.getDataType());
        }
        return false;
    }


    /**
     * 检查参数是够必填或类型是否正确（无嵌套）
     *
     * @param requestParameters
     * @param currentParamsMap
     */
    public String checkRequestParams(String requestParameters, JSONObject currentParamsMap) {
        if (ObjectUtil.isEmpty(currentParamsMap) || StrUtil.isEmpty(requestParameters)) {
            return null;
        }
        StringBuilder message = new StringBuilder();
        try {
            List<JSONObject> dataList = JsonUtil.getJsonToList(requestParameters);
            dataList.forEach(t -> {
                if (StrUtil.isEmpty(message.toString())) {
                    DataInterfaceModel model = JsonUtil.getJsonToBeanSafe(t, DataInterfaceModel.class);
                    if (ObjectUtil.isEmpty(model)) {
                        message.append(StrUtil.format("验证配置参数异常{}！", t));
                    }
                    String value = MapUtil.getStr(currentParamsMap, model.getField());
                    // 验证是否必填
                    if (Constants.TrueKind.equals(String.valueOf(model.getRequired()))) {
                        if (StrUtil.isEmpty(value)) {
                            message.append(model.getField() + "不能为空");
                        }
                    }
                    if (StrUtil.isEmpty(message.toString())) {
                        // 验证类型
                        if (StrUtil.isNotEmpty(model.getFieldType())) {
                            // 判断是整形
                            if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Int.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        Integer.parseInt(value);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为整型");
                                    }
                                }
                            }
                            if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Long.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        Convert.convert(Long.class, value);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为长整型");
                                    }
                                }
                            }
                            if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Bool.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        Convert.convert(Boolean.class, value);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为布尔型");
                                    }
                                }
                            } else if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Decimal.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        Convert.convert(Decimal.class, value);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为高精度小数型");
                                    }
                                }
                            } else if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Float.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        Convert.convert(Float.class, value);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为单精度浮点型");
                                    }
                                }
                            } else if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Double.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        Double.valueOf(value);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为双精度浮点型");
                                    }
                                }
                            } else if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Array.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        JsonUtil.getJsonToJsonArray(value);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为JSON数组类型");
                                    }
                                }
                            } else if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Object.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        JsonUtil.getJsonToBean(value, JSONObject.class);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为JSON对象类型");
                                    }
                                }
                            } else if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Datetime.getValue(), model.getFieldType())) {
                                if (StrUtil.isNotEmpty(value)) {
                                    try {
                                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        formatter.parse(value);
                                    } catch (Exception e) {
                                        message.append(model.getField() + "类型必须为日期时间型");
                                    }
                                }
                            } else if (StrUtil.equalsIgnoreCase(RequestFieldTypeKind.Null.getValue(), model.getFieldType())) {
                                if (ObjectUtil.isNotEmpty(value)) {
                                    message.append(model.getField() + "类型必须为日期时间型");
                                }
                            }
                        }
                    }
                }
            });
        } catch (Exception ex) {
            message.append("参数校验错误，错误提示:" + ex.getMessage());
        }
        return message.toString();
    }
}
